//
//  ucfPlay.m
//  WXIM
//
//  Created by fusuwei on 14-10-15.
//  Copyright (c) 2014年 naren. All rights reserved.
//

#import "ucfPlay.h"


@interface ucfPlay()
{
    //音频参数
    AudioStreamBasicDescription audioDescription;
    // 音频播放队列
    AudioQueueRef audioQueue;
    // 音频缓存
    AudioQueueBufferRef audioQueueBuffers[QUEUE_BUFFER_SIZE];
    
    NSLock *synlock ;///同步控制
    
    Byte *audioByte;
    long audioDataIndex;
    long audioDataLength;
}
@end

@implementation ucfPlay

//回调函数(Callback)的实现
static void BufferCallback(void *inUserData,AudioQueueRef inAQ,AudioQueueBufferRef buffer){
    
    NSLog(@"processAudioData :%u", (unsigned int)buffer->mAudioDataByteSize);
    
    ucfPlay* player=(__bridge ucfPlay*)inUserData;
    
    [player FillBuffer:inAQ queueBuffer:buffer];
}

//缓存数据读取方法的实现
-(void)FillBuffer:(AudioQueueRef)queue queueBuffer:(AudioQueueBufferRef)buffer
{
    if(audioDataIndex + EVERY_READ_LENGTH < audioDataLength)
    {
        memcpy(buffer->mAudioData, audioByte+audioDataIndex, EVERY_READ_LENGTH);
        audioDataIndex += EVERY_READ_LENGTH;
        buffer->mAudioDataByteSize =EVERY_READ_LENGTH;
        AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);
        
        NSLog(@"FillBuffer99999 ");
    }
    
}

-(void)readPCMdataAndPlayData:(NSData*)data
{
    static int lastIndex = 0;
    
    [synlock lock];
    NSInteger readLength = [data length];
    Byte *pcmDataBuffer = (Byte *)[data bytes];
    NSLog(@"readPCMdataAndPlayData size = %ld",(long)readLength);
    
    OSStatus err = noErr;
    
    for (int i=0; i<QUEUE_BUFFER_SIZE; i++) {
        lastIndex=lastIndex+1;
        
        AudioQueueBufferRef cur_fillBuffer = audioQueueBuffers[(lastIndex)%QUEUE_BUFFER_SIZE];
        
        cur_fillBuffer->mAudioDataByteSize = (UInt32)readLength;
        Byte *audiodata = (Byte *)cur_fillBuffer->mAudioData;
        for(int j=0;j<readLength;j++)
        {
            audiodata[j] = pcmDataBuffer[j];
        }
        
        err = AudioQueueEnqueueBuffer(audioQueue, cur_fillBuffer, 0, NULL);
        
        if (err) {
            NSLog(@"theBufferUsed-----%d",lastIndex);
            if (lastIndex > QUEUE_BUFFER_SIZE) {
                lastIndex = 0;
            }
        }
        else
        {
            NSLog(@"theBufferUsed-----%d",lastIndex);
            if (lastIndex > QUEUE_BUFFER_SIZE) {
                lastIndex = 0;
            }

            break;
        }
        
    }
    
    
    
    /*
     将创建的buffer区添加到audioqueue里播放
     AudioQueueBufferRef用来缓存待播放的数据区，AudioQueueBufferRef有两个比较重要的参数，AudioQueueBufferRef->mAudioDataByteSize用来指示数据区大小，AudioQueueBufferRef->mAudioData用来保存数据区
     */
    
    [synlock unlock];
}


-(void)SetAudioFormat
{
    ///设置音频参数
    audioDescription.mSampleRate  = kSamplingRate;//采样率
    audioDescription.mFormatID    = kAudioFormatLinearPCM;
    audioDescription.mFormatFlags =  kAudioFormatFlagIsSignedInteger;//|kAudioFormatFlagIsNonInterleaved;
    audioDescription.mChannelsPerFrame = kNumberChannels;
    audioDescription.mFramesPerPacket  = 1;//每一个packet一侦数据
    audioDescription.mBitsPerChannel   = kBitsPerChannels;//每个采样点16bit量化
    audioDescription.mBytesPerFrame    = kBytesPerFrame;
    audioDescription.mBytesPerPacket   = kBytesPerFrame;
    
    [self CreateAudioQueue];
}



-(void)CreateAudioQueue
{
    [self Cleanup];
    //使用player的内部线程播
    OSStatus err = AudioQueueNewOutput(&audioDescription, BufferCallback, (__bridge void *)(self), nil, nil, 0, &audioQueue);
    NSLog(@"CreateAudioQueue err = %ld",(long)err);
    if(audioQueue)
    {
        ////添加buffer区
        for(int i=0;i<QUEUE_BUFFER_SIZE;i++)
        {
            int result =  AudioQueueAllocateBuffer(audioQueue, EVERY_READ_LENGTH, &audioQueueBuffers[i]);
            ///创建buffer区，MIN_SIZE_PER_FRAME为每一侦所需要的最小的大小，该大小应该比每次往buffer里写的最大的一次还大
            NSLog(@"AudioQueueAllocateBuffer i = %d,result = %d",i,result);
        }
    }
}


-(void)Cleanup
{
    if(audioQueue)
    {
        NSLog(@"Release AudioQueueNewOutput");
        
        [self Stop];
        for(int i=0; i < QUEUE_BUFFER_SIZE; i++)
        {
            AudioQueueFreeBuffer(audioQueue, audioQueueBuffers[i]);
            audioQueueBuffers[i] = nil;
        }
        audioQueue = nil;
    }
}

-(void)Stop
{
    NSLog(@"Audio Player Stop");
    
    AudioQueueFlush(audioQueue);
    AudioQueueReset(audioQueue);
    AudioQueueStop(audioQueue,TRUE);
}

//fusuwei add it for init play
-(void)initPlay
{
    NSLog(@"Audio initPlay");
    [self Stop];
//    audioByte = byte;
//    audioDataLength = len;
    
    NSLog(@"Audio Play Start >>>>>");
    
    [self SetAudioFormat];
    
    AudioQueueReset(audioQueue);
    audioDataIndex = 0;
    for(int i=0; i<QUEUE_BUFFER_SIZE; i++)
    {
        [self FillBuffer:audioQueue queueBuffer:audioQueueBuffers[i]];
    }
    AudioQueueStart(audioQueue, NULL);
}

@end
